/**
 * 
 */
package it.unisalento.appsalento.asynctasc;

import it.unisalento.R;
import it.unisalento.appsalento.Constants.Constants;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.activity.MainActivity;
import it.unisalento.appsalento.asynctask.framework.MIMETypes;
import it.unisalento.appsalento.model.Appello;
import it.unisalento.appsalento.model.GetAppelliResponse;
import it.unisalento.appsalento.model.Request;
import it.unisalento.appsalento.model.Response;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

/**
 * @author AGM
 * 
 */
public class PrenotaEsameAsyncTask extends  AsyncTask<Void, Void, Boolean> {
	protected ProgressDialog progress;
	private String idAppello;
	private final WeakReference<MainActivity> meinActivityWeakRef;
	 
	public PrenotaEsameAsyncTask(String idAppello,MainActivity main ) {
		this.idAppello = idAppello;
		this.meinActivityWeakRef= new WeakReference<MainActivity >(main);
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progress = new ProgressDialog(meinActivityWeakRef.get());
//		progress.setContentView(R.layout.action_progressbar);
		progress.show();

	}
	@Override
	protected void onPostExecute(Boolean result) {
		progress.hide();
		AlertDialog.Builder builder = new AlertDialog.Builder(meinActivityWeakRef.get(),R.style.UniSal_DialogTheme);
		
		if(result){
			builder.setMessage("Appello prenotato con successo") .setTitle("Info");
		}else{
			 builder.setMessage("Appello non prenotato per problemi interni") .setTitle("Warning");
		}
		builder.setNegativeButton("OK",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		});
		builder.show();

	}

	@Override
	protected Boolean doInBackground(Void... params) {
		JSONObject holder = new JSONObject();
		DefaultHttpClient httpclient = new DefaultHttpClient();
		ObjectMapper mapper = new ObjectMapper();
		boolean retVal = false;
		try {
			retVal = setData(holder, httpclient, mapper);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return retVal;
	}
	
	public boolean setData(JSONObject holder,
			DefaultHttpClient httpclient, ObjectMapper mapper)
			throws JSONException, UnsupportedEncodingException, IOException,
			ClientProtocolException, JsonParseException, JsonMappingException {
		boolean retVal = false;
		try {
			Request request = new Request();
			request.setUtente(App.utente);
			request.setIdAppello(idAppello);
			final Gson gson = new GsonBuilder().create();
			final Client client = Client.create();
		    final WebResource resource = client.resource(Constants.URL_REST + Constants.SERVICE_PRENOTA_APPELLO);
		    final ClientResponse response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(ClientResponse.class, gson.toJson(request));
		    if (response.getStatus() != 201 && response.getStatus() != 200) {
		      throw new RuntimeException("failed: http error code = " + response.getStatus());
		    }
		    final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
		    Response prenotazioneResponse = mapper.readValue(responseEntity,Response.class);

			if(prenotazioneResponse != null){
				retVal = prenotazioneResponse.isOk();
			}
		} catch (Throwable t) {
//			App.appelli = new ArrayList<Appello>();
			t.printStackTrace();
		}
		return retVal;
	}

	
}
